var background, touchstart, startShip,
    loader = new Loader();


/**
 * Add events for touches and desktop devices and prevent move page in iphone.
 * Create custom Active state and prevent this active state by adding a data-activatable in your
 * html or data-preventactive also create a fast click by dispatching a custom event
 */
(function(){
	var has = "ontouchstart" in window,
		debugTimer = void(0),
		touches = {
			start: has ? "touchstart": "mousedown",
			touch: has ? "touch": "touch",
			move: has ? "touchmove": "mousemove",
			end: has ? "touchend": "mouseup",
			cancel: has ? "touchcancel": "mouseleave"
		},
		items = document.querySelectorAll("[data-activatable]"),
		prevent = document.querySelectorAll("[data-preventactive]");

	/**
	 * function that dispatch custom event for fast click to item
	 * @param item {Element}
	 */
	function dispatchTouch(item){
		var event = document.createEvent("Event");
		event.initEvent(touches.touch, true, true);
		item.dispatchEvent(event);
	}

	/**
	 * function that gets the element offset in page context
	 * @param el {Element}
	 * @returns {left, top}
	 */
	function getElementPageOffset(el){
		var l = 0, t = 0;

		do{
			l += el.offsetLeft;
			t += el.offsetTop;
		}while(el = el.offsetParent);

		return {left:l, top:t};
	}

	/**
	 * function that return first activatable parent element
	 * @param item {Element}
	 * @returns {Element} activatable element
	 */
	function getParentActivatable(item){
		do{
			if(item.dataset["activatable"]) return item;
		}while(item = item.parentElement);
	}

	/**
	 * Remove custom active state and dispatch fast click event if active item
	 * is equal to current event item
	 * @param e
	 */
	function doEnd(e){
		var active = document.querySelector(".active"),
		//offset = getElementPageOffset(active),
			_item = getParentActivatable(e.target);
		//get parent activatable item and check if is equal to active element
		if(active ===  _item/* && (offset.left === _item.offsetPageLeft && offset.top === _item.offsetPageTop)*/) dispatchTouch(active);
		if(active) active.classList.remove("active");
	}
	/**
	 * Add events to all activatable items
	 */
	Array.prototype.forEach.call(items, function(item){
		item.addEventListener(touches.start, function(){
			/*var offset = getElementPageOffset(item);
			 item.offsetPageLeft = offset.left;
			 item.offsetPageTop = offset.top;*/
			item.classList.add("active");
		});
		item.addEventListener(touches.cancel, function(e){
			var active = document.querySelector(".active");
			active.classList.remove("active");
		});
		item.addEventListener(touches.end, function(e){
			doEnd(e);
		});
	});

	/**
	 * Add start event and stopPropagation to prevent active
	 */
	Array.prototype.forEach.call(prevent, function(item){
		item.addEventListener(touches.start, function(e){
			e.stopPropagation();
		});
	});

	/**
	 * Prevent default move event to remove page moving on iphone
	 */
	window.addEventListener(touches.move, function(e){
		e.preventDefault();
	});

})();

loader.addEventListener("complete", function(){
    game.create(this);
});

loader.loadImages([
    {id: "sBackground", src: "images/Background/starBackground.png"},
    {id: "player", src: "images/player.png"},
    {id: "gLaser", src: "images/laserGreen.png"},
    {id: "gLaserShot", src: "images/laserGreenShot.png"},
    {id: "enemyShip", src: "images/enemyShip.png"},
    {id: "shield", src: "images/shield.png"},
    {id: "playerDamaged", src: "images/playerDamaged.png"},
    {id: "life", src: "images/life.png"},
    {id: "playerExplosion", src: "images/playerExplosion.png"},
    {id: "explosion", src: "images/explosion.png"}
]);

function addRule(rule){
    var lastSheet = document.styleSheets[document.styleSheets.length - 1];
    lastSheet.insertRule(rule, lastSheet.cssRules.length);
}

var levels = [
    {
        enemies: 10,
        enemiesSpeed: [3, 4],
        enemiesRespondTime: [1000, 2000],
        enemiesHealt: 1
    }
];

var game = {

    create : function(loader){
        this.ticker = new Ticker();
        this.loader = loader;
        this.stage = new Stage();
        this.currentLevel = 0;

        this.createStage();

        this.createBackground(this.loader.getResult("sBackground"));
        this.createShip();

        this.ticker.addEventListener("tick", function(){
            game.ship.actions(game.level.enemies);
            game.level.actions();
            game.stage.update();
        });
        //this.startLevel();
    },

    createStage: function(){
        this.stage.create("demoCanvas");
        this.stage.setWidth(window.innerWidth);
        this.stage.setHeight(window.innerHeight);
        this.stage.retina();
        this.stage.loader = loader;
    },

    createShip: function(){
        this.ship = new Ship();

        this.stage.addChild(this.ship);

        this.ship.setImages(this.loader.getResult("player"),
            this.loader.getResult("playerDamaged"),
            this.loader.getResult("playerExplosion"),
            this.loader.getResult("life"));
        this.ship.setBulletImages(this.loader.getResult("gLaser"), this.loader.getResult("gLaserShot"));
        this.ship.setShieldImage(this.loader.getResult("shield"));
        this.ship.opacity(50);
        this.ship.addEventListener("remove", function(){
            game.level.end();
        });
    },

    createBackground: function(background){
        this.stage.canvas.style.backgroundImage = "url("+background.src+")";
        this.stage.canvas.style.backgroundSize = (background.width * 0.5) +"px auto";

        addRule("@-webkit-keyframes background_move { 100% { background-position: 0 "+(background.height * 0.5)+"px; } 0% { background-position: 0 0; } }");
    },

    startLevel: function(){
        document.body.classList.add("start");

        this.level = new Level(levels[this.currentLevel], this);
        this.level.addEventListener("pause", function(){
			game.ticker.pause();
		});
		this.level.addEventListener("resume", function(){
			game.ticker.resume();
		});
		this.level.addEventListener("end", function(){
			game.ticker.stop();
		});
		this.level.addEventListener("complete", function(){
			game.ticker.stop();
			page.end.show();
			page.game.hide();
		});
		this.level.start();
    }
};

var page = {
	menu: new Page(document.getElementById("menu")),
	game: new Page(document.getElementById("game")),
	levels: new Page(document.getElementById("levels")),
	pause: new Page(document.getElementById("pause")),
	options: new Page(document.getElementById("options")),
	end: new Page(document.getElementById("end"))
};

page.end.show();

page.game.addEventListener("beforeShow", function(){
	game.startLevel();
});
page.pause.addEventListener("beforeShow", function(){
	game.level.pause();
});
page.pause.addEventListener("beforeHide", function(){
	game.level.resume();
});

document.getElementById("btn-start-game").addEventListener("touch", function(){
	page.menu.hide();
	page.game.show();
});
document.getElementById("btn-options").addEventListener("touch", function(){
	page.menu.hide();
	page.options.show();
});
document.getElementById("btn-back-menu").addEventListener("touch", function(){
	page.menu.show();
	page.options.hide();
});
document.getElementById("btn-pause").addEventListener("touch", function(){
	page.pause.show();
});
document.getElementById("btn-continue").addEventListener("touch", function(){
	page.pause.hide();
});
document.getElementById("btn-main-menu").addEventListener("touch", function(){
	page.menu.show();
	page.pause.hide();
	page.game.hide();
	game.level.end();
});

function gestureStart(e){
    touchstart = {
        x: e.pageX,
        y: e.pageY
    };
    startShip = {
        x: game.ship.x,
        y: game.ship.y
    };
    e.preventDefault();
}
function gestureMove(e){
    if(!touchstart) return;
    var x = startShip.x - (touchstart.x - e.pageX) * 2,
        y = startShip.y - (touchstart.y - e.pageY) * 2;
    game.ship.moveTo(x, y);
    e.preventDefault();
}
function gestureEnd(){
    touchstart = void 0;
    startShip = void 0;
}

//PC debug
window.addEventListener("mousedown", gestureStart);
window.addEventListener("mousemove", gestureMove);
window.addEventListener("mouseup", gestureEnd);

window.addEventListener("touchstart", gestureStart);
window.addEventListener("touchmove", gestureMove);
window.addEventListener("touchend", gestureEnd);